<template>
  <div class="container">
    <div class="main">
      <div class="main_content">
        <div class="main_header">
          <a-input
            placeholder="查找角色名称"
            style="width: 160px; height: 36px"
            @search="onSearch"
            v-model="searchDetail"
          />
          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="toSearch"
            :disabled="!isAuth(['ROOT', 'ROLE:SELECT'])"
          >
            查询
          </a-button>
          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="addRole"
            v-if="isAuth(['ROOT', 'ROLE:INSERT'])"
          >
            新增
          </a-button>
          <!-- 如果有这个东西 就是true  然后非一下!  就是false 表示不禁用 -->
          <a-popconfirm
            :disabled="!isAuth(['ROOT', 'ROLE:DELETE'])"
            title="是否进行批量删除"
            ok-text="确认"
            cancel-text="取消"
            @confirm="confirm2"
            @cancel="cancel2"
          >
            <a-button
              v-if="isAuth(['ROOT', 'ROLE:DELETE'])"
              type="danger"
              style="margin-left: 10px; width: 98px; height: 36px"
            >
              批量删除
            </a-button>
          </a-popconfirm>
        </div>
        <div class="main_table">
          <a-spin
            size="large"
            v-show="loadingVisible"
            style="loading_icon"
            tip="正在加载中"
          ></a-spin>
          <!-- data-source 数据源,column 列名  row-selection列表项是否可选择	-->
          <!-- rowSelection 是计算属性进行加工处理 -->
          <a-table
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
            :columns="columns"
            :data-source="data"
            :pagination="pagination"
            @change="handleTableChange"
            :rowKey="(record) => record.id"
          >
            <span slot="action" slot-scope="text, record">
              <a
                v-if="isAuth(['ROOT', 'ROLE:UPDATE'])"
                @click="searchItem(record)"
                :class="
                  is_admin == false ? (record.id == 0 ? 'rootColor' : '') : ''
                "
                >修改</a
              >

              <a-divider
                type="vertical"
                v-if="isAuth(['ROOT', 'ROLE:UPDATE'])"
              />
              <a-popconfirm
                :disabled="!isAuth(['ROOT', 'ROLE:DELETE'])"
                title="请选择是否删除该角色"
                ok-text="Yes"
                cancel-text="No"
                @confirm="deleteItem(record)"
                @cancel="cancel(record)"
              >
                <a
                  v-if="isAuth(['ROOT', 'ROLE:DELETE'])"
                  href="#"
                  :class="
                    is_admin == false ? (record.id == 0 ? 'rootColor' : '') : ''
                  "
                  >删除
                </a>
              </a-popconfirm>
              <a-divider
                type="vertical"
                v-if="isAuth(['ROOT', 'ROLE:DELETE'])"
              />
              <a
                v-if="isAuth(['ROOT', 'ROLE:UPDATE'])"
                @click="giverole(record)"
                :class="
                  is_admin == false ? (record.id == 0 ? 'rootColor' : '') : ''
                "
                >分配权限</a
              >
            </span>
          </a-table>
        </div>
      </div>
    </div>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getRoleMessage"
    ></add-or-update>
    <give-role
      v-if="giveRoleVisible"
      ref="giveRole"
      @refreshDataList="getRoleMessage"
    ></give-role>
  </div>
</template>
<script>
import AddOrUpdate from "../components/role-add-or-update.vue";
import giveRole from "../components/role-give-role.vue";
export default {
  components: {
    AddOrUpdate,
    giveRole,
  },
  data() {
    return {
      selectedRowKeys: [], // Check here to configure the default column
      loadingVisible: true,
      // 判断当前的用户是否是超管 如果是 就可以修改自己权限的操作
      is_admin: false,
      //删除中多选中的id列表
      idList: [],
      give_role: false,
      // 搜索内容
      searchDetail: "",
      //   表头的配置条件
      sortedInfo: null,
      //   模态的是否出现
      addOrUpdateVisible: false,
      //   分配权限的模态是否出现
      giveRoleVisible: false,
      // 列名
      columns: [
        // title:列名; dataIndex: 对应数据源中的键值(kay)
        {
          title: "用户名",
          dataIndex: "roleName",
          scopedSlots: { customRender: "roleName" },
        },
        {
          title: "角色名称",
          dataIndex: "desc",
        },
        {
          title: "角色数量",
          dataIndex: "permissions",
        },
        {
          title: "人数",
          dataIndex: "users",
        },
        {
          title: "是否内置用户",
          dataIndex: "systemic",
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
        },
      ],
      // 数据源
      data: [
        //  键值key 对应列名, key为Vue 需要key 可以忽略
      ],
      pagination: {
        position: "bottom",
        pageSize: 10,
        current: 1,
        total: 0,
        pageSizeOptions: ["10", "15", "20", "25"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
      },
    };
  },
  created() {
    this.getRoleMessage();
    // 分页查询数据
    this.searchRole();
    // 查询当前人是否是admin 如果是 admin的话 就解封接口
    this.getCurrentMessage();
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed:123 ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      let ids = [];
      selectedRowKeys.forEach((item) => {
        ids.push(item);
      });
      this.idList = ids;
    },
    async getCurrentMessage() {
      const { data: res } = await this.$http.get("/admin/currentuser");
      console.log(res.data.roles);
      if (res.data.roles.includes("admin")) {
        this.is_admin = true;
      }
    },
    // 批量删除按钮 确认弹框
    confirm2(e) {
      this.mutiDelete();
    },
    // 批量删除按钮 取消弹框
    cancel2() {},

    // 批量删除
    async mutiDelete() {
      this.loadingVisible = true;
      const { data: res } = await this.$http.delete("/admin/roles", {
        data: {
          ids: this.idList,
        },
      });
      if (res.code == 200) {
        this.common.notify("success", "删除成功");
        this.idList.forEach((target) => {
          this.selectedRowKeys = this.selectedRowKeys.filter((item) => {
            return item != target;
          });
        });
        this.idList = this.selectedRowKeys;
        this.pagination.current = 1;
        this.getRoleMessage();
      } else {
        // this.$message.warning("无法删除,请重新选择");
        this.common.notify("warning", "无法删除,请重新选择");
        this.loadingVisible = false;
      }
    },
    // 搜索按钮 查找对应名字的内容
    async toSearch() {
      this.loadingVisible = true;
      if (this.searchDetail == "") {
        this.getRoleMessage();
      } else {
        const { data: res } = await this.$http.get(
          `/admin/roles?roleName=${this.searchDetail}`
        );
        this.loadingVisible = false;
        this.data = res.data.records;
      }
    },
    // 分页点击切换
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      let that = this;
      that.sortedInfo = sorter;
      const pager = { ...that.pagination };
      pager.current = pagination.current;
      that.pagination = pager;
      this.searchRole();
    },
    // 查询按钮
    onSearch(value) {},
    giverole(record) {
      if (this.is_admin == false && record.id == 0) {
        //如果不是超管 点击了超管的分配权限 就不生效
        this.common.notify("warning", "无法分配");
        return;
      }
      console.log(record);
      this.loadingVisible = true;
      this.giveRoleVisible = true;
      this.$nextTick(() => {
        this.$refs.giveRole.update(record);
      });
    },
    // 新增按钮
    addRole() {
      this.loadingVisible = true;
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init();
        // 清空表单 发送请求 获取表单项的部分选择数据.
      });
    },
    // 分页查询
    async getRoleMessage(val) {
      const { data: res } = await this.$http.get("/admin/role/all");
      this.data = res.data;
      this.searchRole();
    },
    // 分页查询显示
    async searchRole() {
      //  `/admin/roles?page=${this.pagination.current}&size=${this.pagination.pageSize}`
      const { data: res } = await this.$http.get("/admin/roles");
      //   必须要是 数字型的
      this.loadingVisible = false;
      this.pagination.total = Number(res.data.total);
      this.data = res.data.records;
    },
    async deleteItem(record) {
      this.loadingVisible = true;
      for (let item of this.data) {
        //  点击行中的用户名 找到 后端返回的数组中 对应用户名的id
        if (item.roleName === record.roleName) {
          if (item.id != 0) {
            let ids = [item.id];
            const { data: res } = await this.$http.delete("/admin/roles", {
              data: {
                ids: ids,
              },
            });
            if (res.code == 200) {
              this.common.notify("success", "删除成功");
              this.selectedRowKeys = this.selectedRowKeys.filter((target) => {
                return target != item.id;
              });
              this.idList = this.selectedRowKeys;
              this.pagination.current = 1;
              this.getRoleMessage();
            }
          } else {
            this.common.notify("warning", "无法删除");
            this.loadingVisible = false;
            // this.$message.warning("无法删除");
          }
        }
      }
    },

    // 模态面板取消按钮触发
    cancel(record, e) {
      this.common.notify("error", "删除失败");

      // this.$message.error("删除失败");
    },
    // 修改表格信息
    async searchItem(record) {
      this.loadingVisible = true;
      if (record.id != 0 || this.is_admin == true) {
        //仅可以修改 id 不为0 ,或者 如果是超管就可以无视id 管所有人
        this.addOrUpdateVisible = true;
        this.$nextTick(() => {
          this.$refs.addOrUpdate.update(record);
        });
      } else {
        this.common.notify("warning", "无法修改");
        // this.$message.warning("无法修改");
      }
    },
  },
  computed: {
    //   表格选中的配置项
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          let ids = [];
          selectedRows.forEach((item) => {
            ids.push(item.id);
          });
          this.idList = ids;
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === "Disabled User", // Column configuration not to be checked
            name: record.name,
          },
        }),
      };
    },
  },
};
</script>
<style  lang='less' scoped>
.container {
  box-sizing: border-box;
  display: flex;
  background-color: #eef1f2;
  // overflow: scroll;
  padding: 35px 75px;

  .main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-items: center;
    // overflow: scroll;
    background-color: #eef1f2;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .main_content {
      padding: 20px;
      padding-top: 20px;
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      .main_header {
        display: flex;
        margin-bottom: 25px;
        .main_table {
          margin-top: 50px;
        }
      }
    }
  }
}
/deep/ .ant-table table {
  text-align: center !important;
}
/deep/ .ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  text-align: center;
}
.rootColor {
  color: #eee;
}
/deep/ .ant-spin-spinning {
  z-index: 100;
  position: absolute;
  top: 50%;
  left: 55%;
}
</style>